package ipsite.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ipsite.data.Data;
import ipsite.data.Memcache;
import ipsite.server.AgeDomain;
import ipsite.server.AlexaUpdate;
import ipsite.server.GetPage;
import ipsite.server.GetTrackIp;
import ipsite.server.GooglePageRank;
import ipsite.server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@SuppressWarnings("serial")
public class UpdateServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");

		String name = Utils.fomatDomain(req.getParameter("name"));

		DBCollection coll = Data.data("domain");

		DBObject domain = coll.findOne(new BasicDBObject("name", name));

		if ((domain != null && domain.get("update") != null && Long
				.parseLong(domain.get("update").toString()) < (new Date()
				.getTime() - 0 * 24 * 60 * 60 * 1000))
				|| (domain != null && domain.get("update") == null)) {
			domain.put("update", new Date().getTime());

			try {
				new GetPage(domain);
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				new GooglePageRank(domain);
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				new AgeDomain(domain);
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			try {
				new AlexaUpdate(domain);
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				new Whois(domain);
			} catch (Exception e) {
				// TODO: handle exception
			}

			try {
				Thread.sleep(10000);
				coll.save(domain);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Memcache.setMemcache("ipsite-last-update", domain.get("name").toString());
		}
	}
}
